﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

namespace ReactiveCode.Linq
{
    using Observables;
    using Util;

    class Projection<TSource, TResult> : UnaryOperator<TSource, TResult>
    {
        Func<IObservable<TSource>, IObservable<TResult>> _resultSelector;

        public Projection(IEnumerableObserver<TResult> observer, Func<IObservable<TSource>, IObservable<TResult>> resultSelector)
            : base(observer)
        {
            Contract.Requires(resultSelector != null);
            _resultSelector = resultSelector;
        }

        protected override Entry OnAdded(IObservable<TSource> item)
        {
            var result = _resultSelector(item);
            Observer.OnAdded(result);
            return new Entry
            {
                Remove = () => Observer.OnRemoved(result)
            };
        }
    }
}
